<template>
  <v-modal
    class="custom-modal"
    v-model:visible="dialogVisible"
    :title="title"
    width="500px"
    @ok="handleSubmit"
    @close="handleClose(false)"
  >
    <el-form
      class="data-form"
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="检查点名称" prop="name">
        <el-input
          class="data-input"
          v-model="form.name"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item label="检查场景" prop="senceId">
        <el-select
          class="search-select"
          v-model="form.senceId"
          placeholder="请选择"
          @change="initTableOptions"
        >
          <el-option
            v-for="(item, index) of dict['inspection_inspection_scene']"
            :key="index"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="场景位置" prop="address">
        <el-input
          class="data-input"
          v-model="form.address"
          placeholder="请输入"
        ></el-input>
      </el-form-item>
      <el-form-item label="经纬度" prop="position">
        <el-input
          class="data-input location-input"
          v-model="form.position"
          placeholder="请输入"
        ></el-input>
        <svg-icon name="location1" size="20px" @click="handleLocation" />
      </el-form-item>
      <el-form-item label="所属园区" prop="areaId">
        <el-select
          class="search-select"
          v-model="form.areaId"
          placeholder="请选择"
          @change="initHouseOptions"
        >
          <el-option
            v-for="item in parkOptions"
            :key="item.pkid"
            :label="item.name"
            :value="item.pkid"
            :disabled="item.enable === '0'"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="关联房屋" prop="houseId">
        <el-select
          class="search-select"
          v-model="form.houseId"
          placeholder="请选择"
        >
          <el-option
            v-for="item in houseOptions"
            :key="item.pkid"
            :label="item.name"
            :value="item.pkid"
            :disabled="item.enable === '0'"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="关联检查表" prop="tableIds">
        <el-select
          class="search-select"
          v-model="form.tableIds"
          placeholder="请选择"
          multiple
        >
          <el-option
            v-for="item in tableOptions"
            :key="item.pkid"
            :label="item.name"
            :value="item.pkid"
            :disabled="item.enabled === '0'"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="检查点图片">
        <VUpload
          listType="picture-card"
          uploadText=""
          accept=".png, .jpg, .jepg"
          v-model="form.files"
        />
      </el-form-item>
      <el-form-item label="是否启用">
        <el-radio-group v-model="form.enabled">
          <el-radio
            v-for="(item, index) of dict['yn']"
            :key="index"
            :value="item.value"
            >{{ item.name }}</el-radio
          >
        </el-radio-group>
      </el-form-item>
    </el-form>
  </v-modal>
  <ChooseLocation
    v-model:dialog-visible="chooseLocationDialogVisible"
    latlnt="106.441091,29.685034"
    @submitLocation="handleChooseLocation"
  />
</template>
<script setup>
import { ref, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import vModal from '@/components/modal/index.vue'
import VUpload from '@/components/upload/index.vue'
import { parkPageList } from '@/api/manager/dataManage/park'
import { getCheckTableList } from '@/api/manager/inspectionManage/checkTableManage.js'
import { buildingPageList } from '@/api/manager/dataManage/building'
import {
  addCheckPoint,
  getCheckPointDetail,
  updateCheckPoint,
} from '@/api/manager/inspectionManage/checkPointManage.js'
import { useDict } from '@/hooks/useDict'
const { dict } = useDict(['yn', 'inspection_inspection_scene'])

defineOptions({
  name: 'AddDialog',
})
const props = defineProps({
  detail: {
    type: Object,
  },
})
watch(
  () => props.detail,
  () => {
    if (props.detail.pkid) {
      handleDetail()
    }
  },
)
const emit = defineEmits(['close'])
const title = ref('')
const dialogVisible = ref(false)
const handleClose = (isFlash) => {
  houseOptions.value = []
  tableOptions.value = []
  form.value = { enabled: '1', files: [] }
  formRef.value.clearValidate()
  dialogVisible.value = false
  emit('close', isFlash)
}
const formRef = ref(null)
const form = ref({ enabled: '1', files: [] })
const rules = ref({
  name: [{ required: true, message: '请输入检查点编号', trigger: 'blur' }],
  senceId: [{ required: true, message: '请选择检查点场景', trigger: 'blur' }],
  address: [{ required: true, message: '请输入场景位置', trigger: 'blur' }],
  areaId: [{ required: true, message: '请选择所属园区', trigger: 'blur' }],
  houseId: [{ required: true, message: '请选择关联房屋', trigger: 'blur' }],
  tableIds: [{ required: true, message: '请选择关联检查表', trigger: 'blur' }],
})

const handleSubmit = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      const params = JSON.parse(JSON.stringify(form.value))
      // 处理附件资料
      if (params.files && params.files.length > 0) {
        params.imageIds = params.files
          .map((i) => {
            return i.pkid
          })
          .join(',')
      } else {
        params.imageIds = ''
      }
      delete params.files

      try {
        let res
        if (form.value.pkid) {
          res = await updateCheckPoint(params)
        } else {
          res = await addCheckPoint(params)
        }
        if (res.success) {
          ElMessage.success('保存成功')
          handleClose(true)
        } else {
          ElMessage.error(res.message)
        }
      } catch (error) {
        console.log('error', error)
      }
    } else {
      ElMessage.warning('请正确录入信息')
    }
  })
}
const handleDetail = async () => {
  const res = await getCheckPointDetail({ pkid: props.detail.pkid })
  if (res.success) {
    res.data.files = res.data.imageFiles || []
    delete res.data.imageFiles
    form.value = res.data
    initHouseOptions(false)
    initTableOptions(false)
  } else {
    ElMessage.error(res.message)
  }
}

const parkOptions = ref([])
const initParkOptions = async () => {
  const res = await parkPageList({
    pageIndex: 1,
    pageSize: 9999,
    parkId: form.value.areaId,
  })
  parkOptions.value = res.data.list
}
const tableOptions = ref([])
const initTableOptions = async (isLoad = true) => {
  const res = await getCheckTableList({
    pageIndex: 1,
    pageSize: 9999,
    senceId: form.value.senceId,
    status: '1',
  })
  tableOptions.value = res.data.list
  if (isLoad) {
    form.value.tableIds = res.data.list.map((i) => {
      return i.pkid
    })
  }
}
const houseOptions = ref([])
const initHouseOptions = async (isReset = true) => {
  const res = await buildingPageList({
    pageIndex: 1,
    pageSize: 9999,
    parkId: form.value.areaId,
  })
  houseOptions.value = res.data.list
  if (isReset) {
    form.value.houseId = ''
  }
}

const chooseLocationDialogVisible = ref(false)
const handleLocation = () => {
  chooseLocationDialogVisible.value = true
}
const handleChooseLocation = (val) => {
  form.value.position = val.longitude + ',' + val.latitude
  chooseLocationDialogVisible.value = false
}
defineExpose({ dialogVisible, title })
watch(
  () => dialogVisible.value,
  (newVal) => {
    if (newVal) {
      initParkOptions()
    }
  },
)
</script>

<style lang="scss"></style>
<style lang="scss" scoped>
.data-form {
  padding: 20px;
}

.svg-icon {
  position: absolute;
  top: 5px;
  right: 10px;
  cursor: pointer;
}
</style>
